<div id="formDiv"></div>
<script type="text/html" id="formContent">
  <form lay-filter="purchasePlanFormContent" id="purchasePlanFormContent" class="layui-form open-form">
    <div class="open-model">
      <div class="open-auto">
        <div>
          <div class="layui-form-item layui-row">
            <input name="id" type="hidden" />
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">委外供应商</label>
              <div class="layui-input-block">
                <select id="supplierId" name="supplierId" lay-filter="supplierId"></select>
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">所属部门</label>
              <!-- <div class="layui-input-block"> -->
              <input name="departmentId" type="hidden" />
              <div class="layui-input-block" id="selectDepartment"></div>
              <!-- <select id="departmentId" name="departmentId" lay-filter="departmentId"></select> -->
              <!-- </div> -->
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">业务类型</label>
              <div class="layui-input-block">
                <!-- 业务类型 1.整体委外 2.工序委外 -->
                <select id="type" name="type" lay-filter="type">
                  <option value="">请选择业务类型</option>
                  <option value="1">整体委外</option>
                  <option value="2">工序委外</option>
                </select>
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">去料加工</label>
              <div class="layui-input-block">
                <!-- 业务类型 1.整体委外 2.工序委外 -->
                <input type="radio" name="isOutSku" value="true" title="是" lay-filter="isOutSku" checked />
                <input type="radio" name="isOutSku" value="false" title="否" lay-filter="isOutSku" />
              </div>
            </div>
          </div>
          <div class="layui-form-item layui-row">
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">预开工日</label>
              <div class="layui-input-block">
                <input class="layui-input" id="startTime" name="startTime" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">预完工日</label>
              <div class="layui-input-block">
                <input class="layui-input" id="endTime" name="endTime" />
              </div>
            </div>
          </div>
        </div>

        <div class="layui-form-item tableContent">
          <!-- {{# if(d.eventName !== 'detail'){ }} -->
          <button class="layui-btn" type="button" id="Configure">配置物料信息</button>
          <!-- {{# } }} -->
          <table class="layui-table" id="purchasePlanFormTable" lay-filter="purchasePlanFormTable"></table>
          <!-- 汇总表 -->
          <table class="layui-table" id="summaryTable" lay-filter="summaryTable"></table>
        </div>

        <div class="layui-form-item text-right" id="BtnBox">
          <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
          <!-- {{# if(d.eventName == 'edit'||d.eventName == 'add'){ }} -->
          <button class="layui-btn" lay-filter="submitBtn" type="button" lay-submit>保存</button>
          <!-- {{# } }} -->
          <!-- {{# if(d.eventName == 'audit'){ }} -->
          <button class="layui-btn" lay-filter="auditPassBtn" type="button" lay-submit>审核通过</button>
          <button class="layui-btn" lay-filter="auditNotPassBtn" type="button" lay-submit>审核不通过</button>

          <!-- {{# } }} -->
        </div>
      </div>
    </div>
  </form>
</script>

<script type="text/html" id="purchasePlanFormTableBar">
  <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" type="button">删除</button>
</script>
<script type="text/html" id="materialListTableBar">
  <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" type="button">删除</button>
</script>
<!-- 物料清单弹窗 -->
<script type="text/html" id="materialListForm">
  <div class="open-form">
    <div class="open-model">
      <div class="open-auto">
        <div>
          <button class="layui-btn layui-btn" id="configureMaterialList">配置物料清单</button>
          <table class="layui-table" id="materialListTable" lay-filter="materialListTable"></table>
        </div>
        <div class="layui-form-item text-right">
          <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
          <button class="layui-btn" id="saveMaterialList" type="button" lay-submit>保存</button>
        </div>
      </div>
    </div>
  </div>
</script>
<script>
  layui.use(["layer", "form", "table", "admin", "laydate", "upload", "laytpl"], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    let laydate = layui.laydate;
    let laytpl = layui.laytpl;
    const nowData = { ...parentData };
    let data = nowData?.data;
    console.log("nowData", nowData, data);

    laytpl(formContent.innerHTML).render({ ...nowData }, function (html) {
      $("#formDiv").after(html);
    });
    const warehouseData = await admin.reqPro("enterprisecab/warehouse/admin/warehouse/list", { limit: 99999 });
    const warehouseList = warehouseData.data;
    if (nowData.eventName == "detail" || nowData.eventName == "audit") {
      admin.setFormDisable("#purchasePlanFormContent", true);
      admin.setFormDisable("#BtnBox", false);
    }
    await admin.initDataSelectPro("enterprise/purchase/admin/supplierInfoPass/list", { limit: 99999 }, "supplierId", "供应商", () => {}, "corporateName");
    admin.initDataSelectTree(true, "user/admin/role/getTreeData", null, "selectDepartment", data ? data.departmentId : null, "责任部门", "departmentId", null);

    // await admin.initDataSelectPro("user/admin/role/list", { limit: 99999, isProduce: false }, "departmentId", "部门", () => {}, "name");
    laydate.render({
      elem: "#startTime",
      type: "datetime",
      max: $("#endTime").val()
    });
    laydate.render({
      elem: "#endTime",
      type: "datetime",
      min: $("#startTime").val()
    });
    form.render("radio");

    let cols = [
      [
        { type: "numbers", title: "序号" },
        { field: "skuCode", align: "center", title: "产品编码" },
        { field: "skuName", align: "center", title: "产品名称" },
        { field: "totalPrice", align: "center", title: "不含税金额", templet: admin.setTableInput("totalPrice", true, "totalPrice") },
        { field: "unitName", align: "center", title: "生产单位" },
        { field: "quantity", align: "center", title: "数量", templet: admin.setTableInput("quantity", nowData.eventName === "detail", "quantity") },
        { field: "remark", align: "center", title: "产出说明", templet: admin.setTableInput("remark") },
        {
          field: "warehouseId",
          align: "center",
          title: "预入仓库",
          templet: admin.setTableSelect(
            "warehouseId",
            warehouseList.map((v) => ({ value: v.id, label: v.name }))
          )
        },
        { field: "price", align: "center", title: "单价", templet: admin.setTableInput("price", nowData.eventName === "detail", "price") },
        { field: "currentCostPrice", align: "center", title: "含税单价", templet: admin.setTableInput("currentCostPrice", true, "currentCostPrice") },
        { field: "taxRate", align: "center", title: "税率", templet: admin.setTableInput("taxRate", nowData.eventName === "detail", "taxRate") },
        { field: "tax", align: "center", title: "税额", templet: admin.setTableInput("tax", true, "tax") },
        { field: "taxTotalPrice", align: "center", title: "含税金额", templet: admin.setTableInput("taxTotalPrice", true, "taxTotalPrice") },
        {
          field: "isChecked",
          align: "center",
          title: "需要检验",
          templet: admin.setTableSelect("isChecked", [
            { value: true, label: "是" },
            { value: false, label: "否" }
          ])
        },
        { field: "warehouseQuantity", align: "center", title: "库存数量" },
        {
          field: "productDetails",
          align: "center",
          title: "添加物料",
          templet: function (d) {
            return `<button class="layui-btn layui-btn-xs layui-btn" lay-event="addMaterial">物料清单</button>`;
          },
          hide: false
        },
        {
          align: "center",
          toolbar: "#purchasePlanFormTableBar",
          title: "操作",
          width: 100,
          hide: nowData.eventName === "detail"
        }
      ]
    ];
    const tableVal = table.render({
      elem: "#purchasePlanFormTable",
      page: false,
      limit: 999999,
      //   height: 400,
      data: [],
      cols: cols,
      done: function () {
        $("#purchasePlanFormContent .layui-table-body").css("overflow", "visible");
        $("#purchasePlanFormContent .layui-table-box").css("overflow", "visible");
        $("#purchasePlanFormContent .layui-table-view").css("overflow", "visible");
        admin.tableInputChange("purchasePlanFormTable");
        function calculate(index, tableData, type) {
      let quantity = Number(tableData[index].quantity || 0); // 数量
      let taxRate = Number(tableData[index].taxRate || 0) / 100; // 税率
      let price = Number(tableData[index].price || 0); // 单价
      let currentCostPrice = (price * (1 + taxRate)).toFixed(6); // 含税单价
      let tax = (price * taxRate * Number(quantity)).toFixed(6); // 税额
      let taxTotalPrice = (Number(currentCostPrice) * Number(quantity)).toFixed(6); // 含税金额
      let totalPrice = (taxTotalPrice - tax).toFixed(6); // 不含税金额
      tableData[index].totalPrice = totalPrice;
      tableData[index].tax = tax;
      tableData[index].currentCostPrice = currentCostPrice;
      tableData[index].taxTotalPrice = taxTotalPrice;
      tableData[index].price = price;
      admin.setTableColHtml("purchasePlanFormTable", index, "totalPrice", tableData[index].totalPrice);
      admin.setTableColHtml("purchasePlanFormTable", index, "tax", tableData[index].tax);
      admin.setTableColHtml("purchasePlanFormTable", index, "currentCostPrice", tableData[index].currentCostPrice);
      admin.setTableColHtml("purchasePlanFormTable", index, "taxTotalPrice", tableData[index].taxTotalPrice);
    }
    admin.tableInputChangeByClass("purchasePlanFormTable", "price", (index, value, tableData, field, tableId) => {
      calculate(index, tableData);
    });
    admin.tableInputChangeByClass("purchasePlanFormTable", "quantity", (index, value, tableData, field, tableId) => {
      calculate(index, tableData);
    });
    admin.tableInputChangeByClass("purchasePlanFormTable", "taxRate", (index, value, tableData, field, tableId) => {
      calculate(index, tableData);
    });
      }
    });

    if (data && data.id) {
      console.log(data);
      form.val("purchasePlanFormContent", data);
      tableVal.reload({
        data: data.productList
      });
      table.render({
        elem: "#summaryTable",
        data: data.groupDetailList,
        cols: [
          [
            { type: "numbers", title: "序号" },
            { field: "skuCode", align: "center", title: "产品编码" },
            { field: "skuName", align: "center", title: "产品名称" },
            { field: "mainUnitName", align: "center", title: "计量单位" },
            { field: "skuSpec", align: "center", title: "规格码" },
            { field: "quantity", align: "center", title: "出库数量" },
            { field: "haveQuantity", align: "center", title: "库存数量" },
          ]
        ]
      });
    } else {
      console.log("123", data);
    }
    form.on("radio(isOutSku)", function (d) {
      cols[0] = cols[0].map((v) => {
        if (v.field == "productDetails") {
          if (d.value == "true") {
            v.hide = false;
          } else {
            v.hide = true;
          }
        }
        return v;
      });
      tableVal.reload({
        cols: cols
      });
    });
    form.on("submit(submitBtn)", function (d) {
      let formData = { ...d.field };
      formData.productList = table.cache["purchasePlanFormTable"];
      if (nowData.eventName == "add") {
        formData.status = "1";
        admin.req(
          "enterprise/product/admin/outsourcingOrder/add",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("outSourTable");
              layer.closeAll("page");
            } else {
              layer.msg(res.msg, { icon: 2, time: 1000 });
            }
          },
          "POST",
          false,
          "application/json"
        );
      } else if (nowData.eventName == "edit") {
        admin.req(
          "enterprise/product/admin/outsourcingOrder/update",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("outSourTable");
              layer.closeAll("page");
            } else {
              layer.msg(res.msg, { icon: 2, time: 1000 });
            }
          },
          "PUT",
          false,
          "application/json"
        );
      }
      return false;
    });
    form.on("submit(auditPassBtn)", function (d) {
      // 弹窗确认是否通过
      layer.confirm("是否确认通过审核？", { icon: 3, title: "提示" }, function (index) {
        layer.close(index);
        admin.req(
          "enterprise/product/admin/outsourcingOrder/audit/" + data.id + "/1",
          {},
          (res) => {
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("outSourTable");
              layer.closeAll("page");
            }
          },
          "POST"
        );
      });
      return false;
    });
    form.on("submit(auditNotPassBtn)", function (d) {
      // 弹窗确认是否不通过
      layer.confirm("是否确认不通过审核？", { icon: 3, title: "提示" }, function (index) {
        layer.close(index);
        admin.req(
          "enterprise/product/admin/outsourcingOrder/audit/" + data.id + "/0",
          {},
          (res) => {
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("outSourTable");
              layer.closeAll("page");
            }
          },
          "POST"
        );
      });
      return false;
    });
    table.on("tool(purchasePlanFormTable)", function (obj) {
      let tableList = table.cache["purchasePlanFormTable"];
      var d = obj.data; // 获取当前行的数据
      var layEvent = obj.event; // 获取事件名（edit 或 del）
      //   if (obj.tr) {
      //     obj.tr.on("click", function (e) {
      //       e.preventDefault(); // 防止默认行为
      //     });
      //   }
      if (layEvent == "del") {
        const index = $(obj.tr[0]).data("index");
        let list = table.cache["purchasePlanFormTable"].filter((v) => {
          return v["LAY_TABLE_INDEX"] != index;
        });
        table.reload("purchasePlanFormTable", {
          data: list
        });
      } else if (layEvent == "addMaterial") {
        let addMaterialForm = admin.formOpen({
          area: ["80%", "70%"],
          offset: "50px",
          title: "添加物料",
          content: $("#materialListForm").html(),
          success: function () {
            let list = d.productDetails || [];
            table.render({
              elem: "#materialListTable",
              data: list,

              cols: [
                [
                  { field: "skuCode", align: "center", title: "产品SKU编号" },
                  { field: "skuName", align: "center", title: "产品名称" },
                  { field: "skuSpec", align: "center", title: "规格码" },
                  { field: "productTypeName", align: "center", title: "产品类型" },
                  { field: "minPrice", align: "center", title: "产品单价" },
                  { field: "baseUnitName", align: "center", title: "基础单位" },
                  { field: "mainUnitName", align: "center", title: "主计价单位" },
                  //操作
                  {
                    align: "center",
                    toolbar: "#materialListTableBar",
                    title: "操作",
                    width: 100
                  }
                ]
              ]
            });
            $("#configureMaterialList").click(function () {
              admin.formOpen({
                area: "90%",
                offset: "50px",
                title: "配置物料清单",
                path: "components/purchase/skuTableForm.html",
                success: function () {
                  parentData.notInListIds = list.map((v) => v.productDetailId).join(",");
                },
                end: function () {
                  if (childData.list) {
                    const newData = childData.list || [];
                    const oldData = table.cache["materialListTable"];
                    console.log(newData, oldData);
                    const list = [...oldData, ...newData];
                    table.reload("materialListTable", {
                      data: list // 设置新的数据
                    });
                  }
                }
              });
            });
          },
          // 完成

          end: function () {
            // table.reload("materialListTable");
            console.log(table.cache["purchasePlanFormTable"]);
          }
        });
        $("#saveMaterialList").click(function () {
          tableList.forEach((v) => {
            if (v.productDetailId == d.productDetailId) {
              v.productDetails = table.cache["materialListTable"];
            }
          });
          layer.close(addMaterialForm);
        });

        return true;
      }
    });
    table.on("tool(materialListTable)", function (obj) {
      let tableList = table.cache["materialListTable"];
      var d = obj.data; // 获取当前行的数据
      var layEvent = obj.event; // 获取事件名（edit 或 del）
      if (layEvent == "del") {
        const index = $(obj.tr[0]).data("index");
        let list = table.cache["materialListTable"].filter((v) => {
          return v["LAY_TABLE_INDEX"] != index;
        });
        table.reload("materialListTable", {
          data: list
        });
      }
    });
    $("#Configure").click(function () {
      admin.formOpen({
        area: "90%",
        offset: "50px",
        title: "配置物料信息",
        path: "components/purchase/skuTableForm.html",
        success: function () {
          parentData.notInListIds = table.cache["purchasePlanFormTable"].map((v) => v.productDetailId).join(",");

          //   parentData.cacheList = [...table.cache["purchaseOrderFormTable"]];
          //   if (parentData.cacheList.length > 0) {
          //     parentData.notInListIds = table.cache["purchaseOrderFormTable"]
          //       .map((v) => {
          //         // if (v.id) return v.id
          //         if (v.productDetailId) return v.productDetailId;
          //       })
          //       .join(",");
          //   } else {
          //     parentData.notInListIds = "";
          //   }
        },
        end: function () {
          if (childData.list) {
            const newData = childData.list || [];
            newData.forEach((v) => {
              v.remark = "";
              v.warehouseQuantity = v.haveQuantity;
              v.unitName = v.mainUnitName;
              v.currentCostPrice = "";
            });
            const oldData = table.cache["purchasePlanFormTable"];
            const list = [...oldData, ...newData];
            table.reload("purchasePlanFormTable", {
              data: list // 设置新的数据
            });
          }
        }
      });
    });
  });
</script>

<style>
  #purchasePlanFormContent .layui-table-cell {
    overflow: visible !important;
  }
  #purchasePlanFormContent .layui-form-label {
    width: 110px;
  }

  #purchasePlanFormContent .layui-input-block {
    margin-left: 140px;
  }

  #purchasePlanFormContent .layui-form-item .layui-inline {
    /* margin-bottom: 5px; */
    margin-right: 0px;
  }
</style>
